package com.lagou.rpc.consumer.controller;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.config.ServerRegistryConfiguration;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import com.lagou.rpc.pojo.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class UserController implements InitializingBean {
    @Autowired
    private ServerRegistryConfiguration serverRegistryConfiguration;

    // 服务代理对象集合，用于发起RPC调用
    private Map<Integer, IUserService> proxyServiceMap = new HashMap<>();

    private AtomicInteger requestProcessed = new AtomicInteger();

    @RequestMapping("/user/{id}")
    public User getUserById(@PathVariable("id") int id) {
        int count = this.requestProcessed.incrementAndGet();
        int serverCount = serverRegistryConfiguration.getServers().size();
        // 通过除留余数法得到目标服务器的索引，拿到相应的服务代理对象，完成RPC调用
        int index = count % serverCount;
        IUserService userService = proxyServiceMap.get(index);
        return userService.getById(id);
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println("服务注册配置信息：" + serverRegistryConfiguration);
        List<ServerRegistryConfiguration.ServerInfo> servers = serverRegistryConfiguration.getServers();
        if (servers == null || servers.isEmpty()) {
            throw new RuntimeException("服务器配置列表不能为空");
        }

        for (int i = 0; i < servers.size(); i++) {
            ServerRegistryConfiguration.ServerInfo serverInfo = servers.get(i);
            IUserService proxy = (IUserService) RpcClientProxy.createProxy(IUserService.class, serverInfo.getIp(), serverInfo.getPort());
            proxyServiceMap.put(i, proxy);
        }
    }
}
